import React from 'react';
import { ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { Spin } from 'antd';

import { getClassListByParentId } from '@/services/goods/class';
import { convertToOptions } from '@/services/Common';

type OneLevelClassProps = {
  form: any;
  extra?: string;
  required?: boolean;
  parentId?: number;
  label?: string;
};

/**
 * 这个组件的作用是为了显示一级组件，可以返回classId与className,所以在外围form中，就不用定义classId与className了
 * @param props 参数
 */
const OneLevelClass: React.FC<OneLevelClassProps> = (props: OneLevelClassProps) => {
  const { parentId, form, extra, required, label } = props;

  // 得到商品分类下拉框的数据
  const [classOptions, setClassOptions] = React.useState<any[] | undefined>(undefined);

  /**
   * 读取取数据库中的数据，并刷新页面
   */
  React.useEffect(() => {
    const initFun = async () => {
      // 检索出一级分类目录
      const topLevelClass = await getClassListByParentId(parentId || 0);
      if (topLevelClass.success) {
        const result = convertToOptions([], topLevelClass.data, 'className', 'classId');
        setClassOptions(result);
      }
    };
    initFun();
  }, []);

  return (
    <>
      {classOptions ? (
        <>
          <ProFormSelect
            name="classId"
            label={label}
            width="md"
            extra={extra}
            fieldProps={{
              options: classOptions,
              // 为了给className赋值
              onChange: (value, option) => {
                if (value) {
                  form.setFieldsValue({ className: option['label'] });
                } else {
                  form.setFieldsValue(undefined);
                }
              },
            }}
            rules={[
              {
                required,
              },
            ]}
          />

          <ProFormText name="className" hidden />
        </>
      ) : (
        <Spin />
      )}
    </>
  );
};

OneLevelClass.defaultProps = {
  parentId: 0,
  required: false,
  label: '分类',
};

export default OneLevelClass;
